﻿using Storage.Admin.Framework.Controllers;
using Storage.Admin.Models;
using Storage.Core.Encyption;
using Storage.Core.Extensions;
using Storage.Services.Bucket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Storage.Core.MediaItem;
using System.IO;
using Storage.Services.BucketImages;
using System.Drawing;
using Storage.Core.Librs;

namespace Storage.Admin.Controllers
{
    [RoutePrefix("image")]
    public class TestImageController : BaseController
    {
        private static string returnDomain = System.Configuration.ConfigurationManager.AppSettings["returnDomain"];

        private IBucketService _bucketService;
        private IMediaItemStorage _mediaItemStorage;
        private IBucketImagesService _bucketImagesService;

        public TestImageController(IBucketService bucketService,
            IMediaItemStorage mediaItemStorage,
            IBucketImagesService bucketImagesService)
        {
            _mediaItemStorage = mediaItemStorage;
            this._bucketImagesService = bucketImagesService;
            this._bucketService = bucketService;
        }

        // GET: TestImage

        /// <summary>
        /// 时效性：有过期时间，开始时间~结束时间，转为：时间戳10位，
        /// apk：用于获取签名秘钥
        /// sig：签名字符串，
        /// file：文件
        /// bucket：存储桶
        /// </summary>
        /// <returns></returns>
        [Route("")]
        public ActionResult Index()
        {
            ViewBag.StartTime = DateTime.Now.toUnix();
            ViewBag.EndTime = DateTime.Now.AddDays(1).toUnix();

            ViewBag.Signature = EncryptorHelper.HmacSha1("8af49e5579146e5b617c43e1d6368b0d", ViewBag.StartTime + "," + ViewBag.EndTime);
            return View();
        }

        /// <summary>
        /// 第一：检查bucket是否存在
        /// 第二：apk的存储
        /// 第三：检验签名
        /// 第四：保存图片
        /// </summary>
        /// <returns></returns>
        [Route("do-up", Name = "uploadImage")]
        [HttpPost]
        public JsonResult UploadImage(UpImgModel model)
        {
            if (!ModelState.IsValid)
            {
                AjaxData.Code = 1005;
                AjaxData.Message = ModelState.getErrMsg();
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }
            if (Request.Files == null || Request.Files.Count == 0)
            {
                AjaxData.Code = 1005;
                AjaxData.Message = "请选择图片文件";
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }
            //图片大小
            var file = Request.Files[0];
            if (file.ContentLength == 0 || !file.isImage())
            {
                AjaxData.Code = 1005;
                AjaxData.Message = "请选择图片文件";
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }
            if (file.isBigSize(1024 * 1024 * 4))
            {
                AjaxData.Code = 1005;
                AjaxData.Message = "图片超过4M";
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }
            //存储桶
            var bucketItem = _bucketService.getByName(model.bucket);
            if (bucketItem == null || !bucketItem.AppStorage.AppKey.Equals(model.apk, StringComparison.InvariantCultureIgnoreCase))
            {
                AjaxData.Code = 1005;
                AjaxData.Message = "存储桶不存在";
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }
            string sig = model.startTime + "," + model.endTime;
            //签名字符串
            string signature = EncryptorHelper.HmacSha1(bucketItem.AppStorage.SecretKey, sig);
            if (!signature.Equals(model.signature, StringComparison.InvariantCultureIgnoreCase))
            {
                AjaxData.Code = 1005;
                AjaxData.Message = "签名未通过";
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }

            string sha1 = FileUitls.GetSHA1(file.InputStream);

            var imgItem = _bucketImagesService.getBySHA1(sha1);
            if (imgItem != null)
            {
                AjaxData.Code = 0;
                AjaxData.Message = "上传成功";
                AjaxData.Data = new { url = imgItem.RelativeUrl };
                return Json(AjaxData, JsonRequestBehavior.DenyGet);
            }

            //保存图片
            //新的文件名称
            string fileName = Guid.NewGuid().ToString().Replace("-", "") + System.IO.Path.GetExtension(file.FileName);
            string timeDir = DateTime.Now.ToString("yyyy-MMdd");
            string ranDir = Guid.NewGuid().to16String();
            //相对路径路径
            //string dir = "/" + bucketItem.AppStorage.RootDirectory + "/" + bucketItem.Name + "/" + (!String.IsNullOrEmpty(model.filePath) ? model.filePath + "/" : "") + timeDir + "/" + ranDir;
            // 存储相对路径文件夹
            string dirPath = Path.Combine("\\", bucketItem.AppStorage.RootDirectory, bucketItem.Name, model.filePath ?? "", timeDir, ranDir);
            //相对路径
            string filePath = file.CreateImagePathFromStream(_mediaItemStorage, dirPath);

            //放地址
            string httpUrl = "/" + bucketItem.Name + "/" + (!String.IsNullOrEmpty(model.filePath) ? model.filePath + "/" : "") + Path.GetFileName(filePath);

            //
            using (Image image = Image.FromStream(file.InputStream))
            {
                _bucketImagesService.insertImage(new Entities.BucketImage()
                {
                    BucketId = bucketItem.Id,
                    CreationTime = DateTime.Now,
                    FileName = Path.GetFileName(file.FileName),
                    IOPath = filePath,
                    Length = file.ContentLength,
                    Height = image.Height,
                    Width = image.Width,
                    RelativeUrl = httpUrl,
                    SHA1 = sha1
                });
            }

            AjaxData.Code = 0;
            AjaxData.Message = "上传成功";
            AjaxData.Data = new { url = returnDomain.TrimEnd('/') + "/cn" + httpUrl };
            return Json(AjaxData, JsonRequestBehavior.DenyGet);
        }



        /// <summary>
        /// 跨域检测
        /// </summary>
        /// <returns></returns>
        [HttpOptions]
        [Route("do-up")]
        public string UploadImage()
        {
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("do-up")]
        public string UpImage()
        {
            return null;
        }



















    }
}